import 'dart:convert';
import 'dart:io';

import 'package:excel/excel.dart';

class ExcelHandler {
  static var codes = [
    'zh-CN',
    'zh-HK',
    'vi-VN',
    'ko-KR',
    'ja-JP',
    'ko-KR',
    'en-US'
  ];
  static final offset = 2;
  static void outoutExcel(Map content, String path) async {
    final excel = Excel.createExcel();
    converExcel(excel, content, 'ROOT');
    File('$path/excel.xlsx')
      ..createSync(recursive: true)
      ..writeAsBytesSync(await excel.encode() ?? []);
  }

  static void converExcel(Excel excel, Map content, String sheet) {
    var sheetObject = excel[sheet];
    sheetObject.appendRow(['KEY', ...codes]);
    var i = 0;
    for (var item in content.entries) {
      if (item.value.isItem(codes)) {
        converItem(sheetObject, item.key, item.value, i);
        i++;
      } else if (item.value is Map) {
        converExcel(excel, item.value, item.key);
      } else if (item.value is List) {
        print(item.value);
      }
    }
  }

  static void converItem(Sheet sheet, String key, Map mapItem, int index) {
    var cell =
        sheet.cell(CellIndex.indexByString('${cellCode(0)}${index + offset}'));
    cell.cellStyle = CellStyle(
      fontSize: 14,
      textWrapping: TextWrapping.WrapText,
    );
    cell.value = key;
    var i = 1;
    for (var code in codes) {
      var cell = sheet
          .cell(CellIndex.indexByString('${cellCode(i)}${index + offset}'));
      cell.cellStyle = CellStyle(
        fontSize: 14,
        textWrapping: TextWrapping.WrapText,
      );
      if (mapItem[code] == null) {
        cell.cellStyle = CellStyle(
          fontSize: 14,
          textWrapping: TextWrapping.WrapText,
          backgroundColorHex: '#FF0000',
        );
        cell.value = '等待翻译';
      } else if (mapItem[code] is String) {
        cell.value = mapItem[code];
      } else {
        cell.value = jsonEncode(mapItem[code]);
      }
      i++;
    }
  }

  static String cellCode(int index) {
    return String.fromCharCode(index + 65);
  }
}
